﻿using I_SheepManagement.Infrastructure;
using I_SheepManagement.Infrastructure.Impls;
using I_SheepManagement.Infrastructure.Interface;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.ComponentModel.Design;
using System.Text;

namespace I_SheepManagement.Read.API.Extensions
{
    public static class ServiceCollectionExtension
    {
        /// <summary>
        /// 注册服务
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public static IServiceCollection AddServices(this IServiceCollection services)
        {
            services.AddScoped<MyDbContext>();
            services.AddTransient(typeof(IRepository<>), typeof(BaseRepository<>));
            services.AddScoped<IDeathManagementRepository, DeathManagementRepository>();
            services.AddScoped<IEliminationManagementRepository, EliminationManagementRepository>();
            return services;
        }

        public static void AddJWT(this IServiceCollection collection, WebApplicationBuilder builder)
        {
            builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(option =>
            {
                //取出私钥
                var secerByte = Encoding.UTF8.GetBytes(builder.Configuration["Authentication:SecreKey"]);
                option.TokenValidationParameters = new TokenValidationParameters()
                {
                    //验证发布者
                    ValidateIssuer = true,
                    ValidIssuer = builder.Configuration["Authentication:Issuer"],
                    //验证验收者
                    ValidateAudience = true,
                    ValidAudience = builder.Configuration["Authentication:Audience"],
                    //验证是否过期
                    ValidateLifetime = true,
                    //验证秘钥
                    IssuerSigningKey = new SymmetricSecurityKey(secerByte)
                };
            });
        }
    }
}
